import { Component } from '@angular/core';
import { NavParams, ViewController } from 'ionic-angular';
import { AuthorizationDetailService } from './detail.service';
import _ from 'lodash';

@Component({
	selector: 'page-authorization-sysDir',
	templateUrl: './sysDir.html',
	providers: [AuthorizationDetailService]
})
export class SysDirPage {
	moa_page_name: any = "page-authorization-sysDir";
	moa_page_explain = "选择权限模块";

	_ = _;

	// 目录
	dirTree = [];
	// 目录树格式化，缓存父节点的路径
	pathTemp = "";

	//

	constructor(
		public navParams: NavParams,
		public viewCtrl: ViewController,
		public detailService: AuthorizationDetailService
	) {
		var that = this;
		this.detailService.getDirDir().subscribe(data => {
			if (data) {
				// 不需要显示的节点
				var needFilteDirId = ["CMFlowgd", "InfoDraft", "InfoClsMgr", "CMAllFile", "CMDraft", "CMRunning", "CMEnd", "CMReject", "CMTermi"];
				this.dirTree = JSON.parse(data).subdir;
				this.formateDir(this.dirTree);
				// 根据dirid过滤掉不显示权限 + 过滤掉权限为空或null的权限
				this.dirTree = _.filter(this.dirTree, function(data) {
					return (!_.includes(needFilteDirId, data["dirid"]) && data["dirname"] != null && data["dirname"] != "")
				})
				// 处理目录树的排序与PC端一致
				this.dirTree = this.order(this.dirTree);

				// 需要选中的
				var needCheckModule = this.navParams.get("module");
				if (needCheckModule && needCheckModule != "") {
					_.forEach(_.split(needCheckModule, ","), function(data) {
						let node = _.find(that.dirTree, { "dirid": data }); // 过滤出选择的节点
						if (node) {
							that.checkChoice(node);
						}
					})
				}
			}
		})

	}

	/**
	 * [order 处理目录树的排序与PC端一致]
	 * @param {[type]} dirTree [description]
	 */
	order(dirTree) {
		var tempDirTree = [];
		var firstFloorNodes = _.filter(dirTree, { "deep": 1 }); // 获得第一层级节点
		_.forEach(firstFloorNodes, function(node) {
			let temp = _.filter(dirTree, function(item) {
				//return _.includes(item["path"],node["dirid"])
				return _.split(item["path"],",")[0] == node['dirid'];
			})
			tempDirTree = _.union(tempDirTree,temp);
		})
		dirTree = tempDirTree;
		return dirTree;
	}

	/**
	 * [formateDir 格式权限目录：1.将每个节点都放在一个数组中；2.每个节点对象增加属性：
	 * 	path路径，isChecked 是否选中，isShow 是否显示，isShowSub 是否展开子列表，hasSub 是否有子节点，deep 所在树深度]
	 * @param {[type]} item [数组对象]
	 */
	formateDir(item) {
		var that = this;
		_.forEach(item, function(data) {
			let temp = {
				"dirid": "",
				"dirname": "",
				"path": "", // 路径，如'发文'的路径： '公文管理,发文'
				"isChecked": false, // 是否选中； ture 选中， false 没选中
				"isShow": false, // 是否显示； ture 页面显示， false 页面不显示
				"isShowSub": false, // 是否展开子列表； ture 展开子列表， false 不展开子列表
				"hasSub": false, // 是否有子节点， true 有 false 没有
				"deep": 1, // 所在树深度，如第一级权限，第二级权限 分别标记为 1，2....
			}

			temp.dirid = data["dirid"];
			temp.dirname = data["dirname"];
			temp.path = (that.pathTemp == "" ? data["dirid"] : that.pathTemp + "," + data["dirid"]);
			temp.deep = _.split(temp.path, ",").length; // 在树的深度;

			if (temp.deep == 1) { // 初始化，深度为1的显示
				temp.isShow = true;
			}

			//console.log(temp.deep + " " +temp.path);

			if (data["subdir"]) { // 有子节点，将子节点放入递归
				temp.hasSub = true; // 更新为有子节点
				that.dirTree.push(temp);
				that.pathTemp = (that.pathTemp == "" ? data["dirid"] : that.pathTemp + "," + data["dirid"]); // 子节点的父节点路径
				that.formateDir(data["subdir"]); // 递归
			} else {
				that.dirTree.push(temp);
			}

		});

		this.pathTemp = _.toString(_.dropRight(_.split(this.pathTemp, ","), 1)); // 返回上一层路径
	}


	/**
	 * [checkShowSub 展开或收起子节点]
	 * @param {[type]} item [description]
	 */
	checkShowSub(item) {
		if (item["isShowSub"]) { // 原来是显示的，则子节点子子节点...修改成不显示
			let childNodes = this.getAllChildNodes(item); // 获得所有子节点

			_.forEach(childNodes, function(data) {
				data["isShow"] = false;
				data["isShowSub"] = false; // 是否展开子列表,修改为false
			})
		} else { // 显示子节点且只显示下一层，子子节点不显示
			let subNode = this.getNextFloorSubNodes(item); // 获得下一层节点
			_.forEach(subNode, function(data) {
				data["isShow"] = true;
			});

		}

		// 更新下拉或收起状态
		item["isShowSub"] = !item["isShowSub"];
	}


	/**
	 * [checkChoice 选择权限]
	 * @param {[type]} item [description]
	 */
	checkChoice(item) {
		this.setChoiceFatherFloor(item);
		//item["isChecked"] = !item["isChecked"];
		this.setChoiceChildFloor(item, item["isChecked"]);
	}

	/**
	 * [setChoiceChildFloor 设置子节点选择状态]
	 * @param {[type]} item [description]
	 * @param {[boolean]} isChecked [ture 子节点设置成选择,false子节点去掉选择]
	 */
	setChoiceChildFloor(item, isChecked) {
		var that = this;
		// 将要修改成的状态
		var status = isChecked;
		// 下层子节点
		let childNodes = this.getNextFloorSubNodes(item);

		item["isChecked"] = status;
		if (status) { // 修改成选中状态
			if (item["hasSub"]) { // 将子节点和子子节点...修改成选中状态

				// 设置子节点显示或隐藏
				_.forEach(childNodes, function(data) {
					if (data["hasSub"]) {
						that.setChoiceChildFloor(data, true);
					} else {
						data["isChecked"] = status;
					}
				});
			}
		} else { // 修改成未选中状态
			// 将子节点修改成未选择状态
			if (item["hasSub"]) {
				// 设置子节点显示或隐藏
				_.forEach(childNodes, function(data) {
					if (data["hasSub"]) {
						that.setChoiceChildFloor(data, false);
					} else {
						data["isChecked"] = status;
					}
				});
			}
		}
	}

	/**
	 * [setChoiceFatherFloor 设置父节点选择状态]
	 * @param {[type]} item [description]
	 */
	setChoiceFatherFloor(item) {
		// 将要修改成的状态 false 修改成未选择状态，true 修改成选择状态
		var status = item["isChecked"] ? false : true;
		var sameFloorNodes = this.getSameFloorNodes(item);
		var fatherNode = this.getFatherNode(item);

		item["isChecked"] = status; // 设置当前节点选择状态
		//console.log(sameFloorNodes);
		//console.log(fatherNode);

		if (fatherNode != null) { // 存在父节点
			if (status) { // 修改成选择状态
				// 同一层级未选中的节点大于1，则父节点不用设置为选中,否则父节点设置为选中状态
				if (_.filter(sameFloorNodes, { "isChecked": false }).length == 0) {
					if (this.getFatherNode(fatherNode) != null) { // 如果父节点还有父节点，则进入递归
						this.setChoiceFatherFloor(fatherNode);
					} else { // 如果父节点没有父节点了，设置成选择状态
						fatherNode["isChecked"] = status;
					}
				}
			} else { //修改成未选择状态
				// 同一层级未的节点都是选中状态，则父节要修改成未选择状态，否则不用
				if (_.filter(sameFloorNodes, { "isChecked": false }).length == 1) {
					if (this.getFatherNode(fatherNode) != null) { // 如果父节点还有父节点，则进入递归
						this.setChoiceFatherFloor(fatherNode);
					} else { // 如果父节点没有父节点了，设置成选择状态
						fatherNode["isChecked"] = status;
					}
				}
			}
		}
	}



	/**
	 * [getNextFloorSubNodes 获得下一层子节点]
	 * @param {[type]} item [数组对象]
	 */
	getNextFloorSubNodes(item) {
		// 选择的节点的路径
		var currentPath = item["path"];
		// 选择的节点的深度
		var currentDeep = item["deep"];
		// 获得比当前节点深一层的节点并且路径包含父节点路径的节点，即选择节点的下一层子节点
		return _.filter(this.dirTree, function(data) {
			return (data["deep"] == currentDeep + 1) && (_.toString(_.dropRight(_.split(data["path"], ","))) == currentPath);
		});
	}

	/**
	 * [getFatherNodes 获得父节点]
	 * @param {[type]} item [对象]
	 */
	getFatherNode(item) {
		var retVal = null;
		// 选择的节点的路径
		var currentPath = item["path"];
		// 选择的节点的深度
		var currentDeep = item["deep"];


		if (currentDeep > 1) { // 深度不大于1，即没有父节点
			let fatherPath = _.toString(_.dropRight(_.split(currentPath, ",")));
			retVal = _.filter(this.dirTree, function(data) {
				return (data["deep"] == (currentDeep - 1)) && (data["path"] == fatherPath);
			})[0];
		}

		return retVal;
	}

	/**
	 * [getSameFloorNodes 获得同层的节点]
	 * @param {[type]} item [数组对象]
	 */
	getSameFloorNodes(item) {
		//console.log("##authorization.sysDir.getSameFloorNodes 获得同层的节点")
		var retVal = [];
		// 选择的节点的路径
		var currentPath = item["path"];
		// 选择的节点的深度
		var currentDeep = item["deep"];
		// 父节点路径
		var fatherPath = _.toString(_.dropRight(_.split(currentPath, ",")));

		if (fatherPath) {
			retVal = _.filter(this.dirTree, function(data) {
				return (data["deep"] == currentDeep) && (_.toString(_.dropRight(_.split(data["path"], ","))) == fatherPath);
			});
		}
		return retVal;
	}

    /**
     * [getAllChildNode 获取所有的子节点]
     * @param {[type]} item [数组对象]
     */
	getAllChildNodes(item) {
		var path = item["path"];
		var deep = item["deep"];

		return _.filter(this.dirTree, function(data) {
			return (data["deep"] > deep) && (_.toString(_.dropRight(_.split(data["path"], ","), data["deep"] - deep)) == path);
		});
	}

	/**
	 * [retValHandle 处理返回结果，如：选择父节点，则子节点不需要返回]
	 */
	retValHandle() {
		var retVal = {
			"module": "",
			"moduleName": ""
		}
		let checkedNodes = _.filter(this.dirTree, { "isChecked": true });

		if (checkedNodes && checkedNodes.length > 0) { // 有选择节点
			if (_.find(checkedNodes, { "hasSub": true })) { // 有选中父节点类型的节点,则进入删除子节点
				checkedNodes = this.dropNode(checkedNodes);
			}

			retVal.module = _.toString(_.map(checkedNodes, "dirid"));
			retVal.moduleName = _.toString(_.map(checkedNodes, "dirname"));
		}

		return retVal;
	}

	dropNode(nodes) {
		var needDropNodes = [];
		var hasSubNodes = _.filter(nodes, { "hasSub": true });
		if (hasSubNodes) {
			_.forEach(hasSubNodes, function(data) {
				let path = data["path"];
				let deep = data["deep"];

				let temp = _.filter(nodes, function(data) { // 查找父节点下的子节点
					return (data["deep"] == (deep + 1)) && (_.toString(_.dropRight(_.split(data["path"], ","), data["deep"] - deep)) == path);
				})

				needDropNodes = _.union(needDropNodes, temp);
			})

			if (needDropNodes) {
				nodes = _.pullAll(nodes, needDropNodes);
				//console.log(nodes);
				// _.forEach(needDropNodes, function(data) { // 删除父节点下的子节点
				// 	nodes = _.dropRightWhile(nodes, { "dirid": data["dirid"] })
				// 	console.log(nodes);
				// })

			}
		}

		return nodes;
	}

	complete() {
		this.viewCtrl.dismiss(this.retValHandle());
	}

	dismiss(data?: any) {
		this.viewCtrl.dismiss(null);
	}


	selectChange(index) {

	}
}

